<template>
  <div>
    <el-card>
      <div class="card">
        <el-steps :active="active" finish-status="success">
          <el-step title="商品基本信息"></el-step>
          <el-step title="添加库存信息"></el-step>
          <el-step title="添加移动端详情"></el-step>
        </el-steps>
      </div>
    </el-card>
    <el-card>
      <el-form
        ref="form"
        class="form"
        :rules="rules"
        :model="form"
        label-width="100px"
      >
        <div v-if="active === 1">
          <div class="title">基本信息</div>
          <el-divider></el-divider>
          <div class="main">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item prop="name" label="商品名称" size="small">
                  <el-input v-model="form.name" class="myInput" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="productSn" label="商品编码" size="small">
                  <el-input v-model="form.productSn" class="myInput" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="商品分类" size="small">
                  <el-select
                    v-model="form.productCategoryId"
                    class="myInput"
                    placeholder="商品分类"
                    clearable
                  >
                    <el-option
                      v-for="item in productCategoryList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="商品品牌" size="small">
                  <el-select
                    v-model="form.brandId"
                    class="myInput"
                    clearable
                    placeholder="品牌"
                  >
                    <el-option
                      v-for="item in brandList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="16" :offset="0">
                <el-form-item label="商品描述" size="small">
                  <el-input
                    v-model="form.description"
                    type="textarea"
                    class="myInput"
                    placeholder="商品描述"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 商品属性 -->
            <div class="title">商品属性</div>
            <el-divider></el-divider>
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="商品原价" size="small">
                  <el-input-number
                    v-model="form.originalPrice"
                    class="myInput"
                    placeholder="商品原价"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="促销类型" size="small">
                  <el-select
                    v-model="form.promotionType"
                    class="myInput"
                    placeholder="促销类型"
                    clearable
                    disabled
                  >
                    <el-option
                      v-for="(item, index) in promotionTypeList"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="活动价格" size="small">
                  <el-input-number
                    v-model="form.price"
                    disabled
                    class="myInput"
                    placeholder="当前价格"
                    type="number"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="重量(kg)" size="small">
                  <el-input-number
                    v-model="form.weight"
                    class="myInput"
                    placeholder="重量"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="8" :offset="0">
                <el-form-item label="审核状态" size="small">
                  <el-switch
                    v-model="form.verifyStatus"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8" :offset="0">
                <el-form-item label="是否上架" size="small">
                  <el-switch
                    v-model="form.publishStatus"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-form-item label="缩略图" size="small">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="addTiImg"
                >
                  <img v-if="form.pic" :src="form.pic" class="pic" />
                  <i v-else class="el-icon-plus pics" />
                </el-upload>
              </el-form-item>
            </el-row>
            <!-- 其他信息 -->
            <div class="title">其他信息</div>
            <el-divider></el-divider>
            <el-row :gutter="30">
              <el-col :span="8" :offset="0">
                <el-form-item label="推荐状态" size="small">
                  <el-switch
                    v-model="form.recommendStatus"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="新品状态" size="small">
                  <el-switch
                    v-model="form.newStatus"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item label="预告商品" size="small">
                  <el-switch
                    v-model="form.previewStatus"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="搜索关键词"
                  size="small"
                  label-width="100px"
                >
                  <el-input
                    v-model="form.keywords"
                    class="myInput"
                    placeholder="关键词"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="库存预警" size="small">
                  <el-input-number v-model="form.lowStock" class="myInput" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="商品排序" size="small">
                  <el-input-number
                    v-model="form.sort"
                    class="myInput"
                    placeholder="排序"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="16" :offset="0">
                <el-form-item label="产品服务" size="small">
                  <el-checkbox-group v-model="services">
                    <el-checkbox label="1" name="type">无忧退货</el-checkbox>
                    <el-checkbox label="2" name="type">快速退款</el-checkbox>
                    <el-checkbox label="3" name="type">免费包邮</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div v-if="active === 2">
          <div class="title">商品sku信息</div>

          <el-divider></el-divider>
          <div class="main">
            <el-row :gutter="30">
              <el-col :span="8" :offset="0">
                <el-form-item label="标题" size="small">
                  <el-input v-model="form.detailTitle" placeholder="标题" />
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="副标题" size="small">
                  <el-input v-model="form.detailDesc" placeholder="副标题" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item class="albumPics" label="画册图片" size="small">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :on-remove="imgRemove"
                :file-list="fileList"
                :on-success="uploadImg"
                :limit="5"
                :on-preview="imgPreview"
                list-type="picture-card"
              >
                <i class="el-icon-plus" />
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb,文件不超过5个
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="sku设置">
              <div v-show="skuObj.color.list.length > 0" style="display: flex">
                颜色：
                <el-checkbox-group v-model="skuObj.color.selList">
                  <el-checkbox
                    v-for="(item, index) in skuObj.color.list"
                    :key="index"
                    :label="item"
                    >{{ item }}
                    <el-button
                      size="mini"
                      type="text"
                      style="color: red; margin-left: 10px"
                      @click="delParam(index, 'color')"
                      >删除</el-button
                    >
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-show="skuObj.size.list.length > 0" style="display: flex">
                大小：
                <el-checkbox-group v-model="skuObj.size.selList">
                  <el-checkbox
                    v-for="(item, index) in skuObj.size.list"
                    :key="index"
                    :label="item"
                    >{{ item }}
                    <el-button
                      size="mini"
                      type="text"
                      style="color: red; margin-left: 10px"
                      @click="delParam(index, 'size')"
                      >删除</el-button
                    >
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div style="display: flex">
                <el-input
                  v-model="skuObj.color.text"
                  style="display: inline-block; width: 200px"
                  placeholder="请填写颜色(比如:土豪金)"
                  size="mini"
                  clearable
                  class="ipts"
                />
                <el-button
                  size="mini"
                  @click="addSkuAtr('color')"
                  class="addbtns"
                  >创建颜色选项</el-button
                >
                <el-input
                  v-model="skuObj.size.text"
                  style="display: inline-block; width: 200px"
                  placeholder="请填写大小(比如:中号)"
                  size="mini"
                  clearable
                  class="ipts"
                />
                <el-button
                  size="mini"
                  @click="addSkuAtr('size')"
                  class="addbtns"
                  >创建大小选项</el-button
                >
                <div class="skuBtns">
                  <el-button type="primary" size="mini" @click="createSku"
                    >生成sku列表</el-button
                  >
                  <el-button type="primary" size="mini" @click="addSku"
                    >新增sku</el-button
                  >
                </div>
              </div>
            </el-form-item>
            <el-table
              size="mini"
              :data="skuTableList"
              border
              stripe
              v-if="tableShow"
            >
              <el-table-column type="index" label="#" fixed="left" />

              <el-table-column label="图片" :width="120">
                <template slot-scope="scope">
                  <el-upload
                    style="width: 100px; height: 100px"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :show-file-list="false"
                    :on-success="addTiImg"
                    @click.native="saveSku(scope.row)"
                  >
                    <img
                      v-if="scope.row.pic"
                      style="width: 100px; height: 100px"
                      :src="scope.row.pic"
                      class="avatar"
                    />
                    <i
                      v-else
                      style="width: 100px; height: 100px; margin-top: -31px"
                      class="el-icon-plus avatar-uploader-icon"
                    />
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="颜色" :width="160">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.color" size="mini" v-if="skuFlags"/>
                    <el-input v-model="scope.row.spData[0].value" size="mini" v-if="skuFlag"/>
                </template>
              </el-table-column>
              <el-table-column label="大小" :width="160">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.size" size="mini" v-if="skuFlags"/>
                   <el-input v-model="scope.row.spData[1].value" size="mini" v-if="skuFlag"/>
                </template>
              </el-table-column>
              <el-table-column label="库存" :width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.stock"
                    size="mini"
                    placeholder="自定义库存"
                  />
                </template>
              </el-table-column>
              <el-table-column label="预警库存" :width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.lowStock"
                    size="mini"
                    placeholder="预警库存"
                  />
                </template>
              </el-table-column>
              <el-table-column label="锁定库存" :width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.lockStock"
                    size="mini"
                    placeholder="锁定库存"
                  />
                </template>
              </el-table-column>
              <el-table-column label="sku编码" :width="200">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.skuCode"
                    size="mini"
                    placeholder="自定义sku编码"
                  />
                </template>
              </el-table-column>
              <el-table-column label="价格" :width="160">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.price"
                    size="mini"
                    placeholder="价格,单位:分"
                  />
                </template>
              </el-table-column>
              <el-table-column label="销量" :width="160">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.sale" size="mini" />
                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" :width="160">
                <template slot-scope="scope">
                  <span>
                    <el-button
                      style="color: red"
                      size="mini"
                      type="text"
                      @click="delNewSku(scope.row)"
                      >删除
                    </el-button>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-if="active === 3">
          <div class="title">详情描述</div>
          <el-divider></el-divider>
          <div class="">
            <quill-editor
              v-model="content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)"
            >
            </quill-editor>
          </div>
        </div>
        <el-divider></el-divider>
        <div class="btns">
          <el-button
            v-show="active > 1"
            class="btn"
            size="small"
            @click="preBtn"
            >返回上一步
          </el-button>
          <el-button
            v-show="active < 3"
            size="small"
            class="submit_button"
            type="primary"
            @click="nextBtn"
            >{{ nextBtnText }}
          </el-button>
          <el-button
            v-show="active == 3"
            size="small"
            class="submit_button"
            type="primary"
            @click="onSubmit"
            >提交保存</el-button
          >
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { findAllbrand } from "@/api/market";
import {
  getAllCategory,
  addProductAndSkus,
  productSkusDetail,
  updateProductAndSkus,
} from "@/api/product";
import mixin from "@/minx/index";
import { uuid } from "vue-uuid";
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  props: {},
  mixins: [mixin],
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      active: 1,
      form: {
        productSn: "",
        name: "", // 名字
        brandId: "", // 品牌ID
        price: "", // 当前价格
        originalPrice: "", // 原价
        sort: "", // 排序
        keywords: "", // 关键词
        description: "", // 商品描述
        note: "", // 商品备注
        deleteStatus: "0", // 删除状态
        newStatus: "0", // 新品状态
        previewStatus: "0", // 是否预告商品
        publishStatus: "0", // 是否上架
        recommendStatus: "1", // 是否推荐
        verifyStatus: "1", // 审核状态
        weight: "", // 商品重量 单位千克
        detailTitle: "", // 标题
        detailDesc: "", // 副标题
        pic: "", // 展示图片
        lowStock: "", // 库存预警 doing
        productAttributeCategoryId: "", // 属性分类
        productCategoryId: "", // 商品分类
        promotionType: 0, // 促销类型
      },
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
      },
      productCategoryList: [],
      brandList: [],
      promotionTypeList: [
        { name: "没有促销使用原价", id: 0 },
        { name: "使用促销价", id: 1 },
        { name: "使用会员价", id: 2 },
        { name: "使用阶梯价格", id: 3 },
        { name: "使用满减价格", id: 4 },
        { name: "限时购", id: 5 },
      ],
      services: [],
      fileList: [],
      skuObj: {
        color: {
          text: "",
          list: [], // 颜色列表
          selList: [], // 选中的颜色
        },
        size: {
          text: "",
          list: [], // 大小列表
          selList: [], // 选中的大小
        },
      },
      skuList: [],
      skuTableList: [],
      tableShow: false,
      content: "",
      editorOption: {},
      sKuopic: {},
      id: "",
      tempSkuList: [],
      skuFlag:false,
      skuFlags:true
    };
  },
  computed: {
    nextBtnText() {
      let text = "";
      switch (this.active) {
        case 1:
          text = "下一步,填写库存信息";
          break;
        case 2:
          text = "下一步,填写移动端详情";
          break;
        default:
          break;
      }
      return text;
    },
  },
  created() {
    this.init();
    this.getCategoryList();
    this.id = this.$route.query.ids;
    if (this.id) {
      this.getDetail();
    }
  },
  mounted() {},
  watch: {},
  methods: {
    //获取品牌列表
    async init() {
      this.brandList = (await findAllbrand()).data.items;
    },
    //获取分类列表
    getCategoryList() {
      getAllCategory().then((res) => {
        if (res.success) {
          res.data.items.forEach((item) => {
            if (item.category.name === "乐居") {
              this.productCategoryList = item.children;
            }
          });
        }
      });
    },
    //获取商品详情
    getDetail() {
      productSkusDetail(this.id).then((res) => {
        console.log(res)
        this.form = res.data.product;
        res.data.skus.forEach((item) => {
          this.skuTableList.push({
            ...item,
            spData: JSON.parse(item.spData),
          });
          this.tempSkuList.push({
            ...item,
            spData: JSON.parse(item.spData),
          });
        });
        if (this.form.albumPics) {
          const imgArr = this.form.albumPics.split(",");
          imgArr.forEach((item) => {
            this.fileList.push({
              url: item,
            });
          });
        }
        if (this.form.services && this.form.services.length > 0) {
          this.services = this.form.services.split(",");
        }
        this.content=this.form.detailMobileHtml
      });
      this.tableShow=true
      this.skuFlags=false
      this.skuFlag=true
    },
    //上传缩略图
    addTiImg(res) {
      if (res.success) {
        this.form.pic = res.data.fileUrl;
      }
      this.skuTableList.forEach((el) => {
        if (el === this.sKuopic) {
          el.pic = res.data.fileUrl;
        }
      });
    },

    //返回上一步
    preBtn() {
      this.active--;
    },
    //下一步
    nextBtn() {
      this.active++;
    },

    //上传图片
    uploadImg(res) {
      if (res.success) {
        this.fileList.push({ url: res.data.fileUrl });
        this.$message.success("上传成功");
        // console.log(this.fileList)
      } else {
        this.$message.error("上传失败");
      }
    },
    //预览
    imgPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //删除照片
    imgRemove(file) {
      this.fileList = this.fileList.filter((item) => {
        return item.url != file.url;
      });
      // console.log(this.fileList)
    },
    addSkuAtr(atrName) {
      if (this.skuObj[atrName].text) {
        this.skuObj[atrName].list.push(this.skuObj[atrName].text);
        this.skuObj[atrName].text = "";
        // console.log(this.skuObj.color.selList)
      }
    },
    delParam(index, atrName) {
      // console.log(atrName);
      this.skuObj[atrName].list.splice(index, 1);
      this.skuObj[atrName].selList.splice(index,1)

    },
    // 生成sku
    createSku() {
      var list = [
        // [...this.skuObj.color.selList],
        // [...this.skuObj.size.selList],
      ];

      for (var key in this.skuObj){
        if(this.skuObj[key].selList.length>0){
          list.push([...this.skuObj[key].selList])
          // list =[...this.skuObj[key].selList]
        }
      }
      if(list.length===0){
        this.$message.error('请选择颜色')
        return false
      }
      // this.skuList = list.reduce((current, total) => {
      //   var skuList = [];
      //   total.forEach((out) => {
      //     current.forEach((inner) => {
      //       if (typeof out === "object") {
      //         skuList.push([...out, inner]);
      //       } else {
      //         skuList.push([out, inner]);
      //       }
      //     });
      //   });
      //   return skuList;
      // });
// console.log(...list)
   this.skuList= this.cartesianProductOf(...list)
 this.createSkuTableList();

    },
    cartesianProductOf() {

    return Array.prototype.reduce.call(arguments, (a, b) =>{
        var ret = [];
        a.forEach(a=> {
            b.forEach((b)=> {
                ret.push(a.concat([b]));
            });
        });
        return ret;
    }, [[]]);
},


    saveSku(el) {
      this.sKuopic = el;
    },
    //生成sku表单
    createSkuTableList() {
      this.skuList.forEach((item, index) => {
        var obj = {
          lowStock: 0,
          lockStock: 0,
          price: 0,
          skuCode: "111",
          stock: 0,
          pic: "", // 上传图片
          size: item[1], // 第一个是大小
          color: item[0], // 第二个是颜色
          tempId: uuid.v1(), // 暂存id
          sale: 999,
        };
        this.skuTableList.push(Object.assign({}, obj));

        console.log(this.skuTableList);
        this.tableShow = true;
      });
    },
    // 新增sku
    addSku() {
      this.createSku();
    },
    // 删除sku
    delNewSku(el) {
      this.$confirm("此操作将永久删除该sku, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var index = this.skuTableList.findIndex(
            (item) => item.tempId === el.tempId
          );
          this.skuTableList.splice(index, 1);
          if(this.skuTableList.length===0){
            this.tableShow=false
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    onEditorReady(editor) {
      // 准备编辑器
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {
      console.log(this.content);
    }, // 内容改变事件
    // 提交
    onSubmit() {
      var brandName = "";
      var productCategoryName = "";
      this.brandList.forEach((item) => {
        if (item.id === this.form.brandId) {
          brandName = item.name;
        }
      });
      this.productCategoryList.forEach((item) => {
        if (item.id === this.form.productCategoryId) {
          productCategoryName = item.name;
        }
      });
      this.skuTableList.forEach((item) => {
        delete item.tempId;
        var apDataArr = [
          {
            key: "颜色",
            value: item.color,
          },
          {
            key: "大小",
            value: item.size,
          },
        ];
        // console.log(apDataArr)
        item.spData = JSON.stringify(apDataArr);
        delete item.color;
        delete item.size;
      });
      const albumPicsArr = this.fileList.map((item) => item.url);
      if (!this.id) {
        addProductAndSkus({
          pmsSkuStockList: this.skuTableList,
          product: {
            ...this.form,
            brandName,
            productCategoryName,
            detailMobileHtml: this.content,
            albumPics: albumPicsArr.join(","),
            services: this.services.join(","),
          },
        }).then((res) => {
          if (res.success) {
            this.$message.success("添加成功");
            this.$router.push({ path: "/product/list" });
          }
        });
      } else {
        updateProductAndSkus({
          pmsSkuStockList: this.skuTableList,
          product: {
            ...this.form,
            brandName,
            productCategoryName,
            detailMobileHtml: this.content,
            albumPics: albumPicsArr.join(","),
            services: this.services.join(","),
          },
        }).then((res) => {
          if (res.success) {
            this.$message.success("编辑成功");
            this.$router.push({ path: "/product/list" });
          }
        });
      }
    },
  },

  components: {
    quillEditor,
  },
};
</script>

<style lang="scss" scoped>
.pic,
.pics {
  width: 200px;
  height: 200px;
}
.pics {
  font-size: 28px;
  color: #8c939d;
  line-height: 200px;
}
.btns {
  display: flex;
  justify-content: center;
  align-items: center;
}
.addbtns {
  margin-left: 20px;
}
.ipts {
  margin-left: 20px;
}
.skuBtns {
  margin-left: 200px;
}
</style>
